package com.hspedu.outputstream;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.io.*;

/**
 * @Author Stringzhua
 * @Date 2024/3/16 16:43
 * description:文件拷贝
 */
public class FileCopy {
    public static void main(String[] args) {
        //完成文件拷贝,将e:\\Koala.jpg 拷贝 d:\\
        /*
         * 思路分析:
         * 1.创建文件输入流,将文件读入到程序
         * 2.创建文件输出流,将读取到的文件输出到指定的路径
         * */
        String srcfilePath = "e:\\qiyeke\\filecontroller\\Koala.jpg";
        String destfilePath = "e:\\qiyeke\\filecontroller\\Koala1.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcfilePath);
            fileOutputStream = new FileOutputStream(destfilePath, true);//文件拷贝时,这里的true没有防止文件被覆盖的作用

            //定义一个字节数组,提高读取效率
            byte[] buf = new byte[1024];
            int reanLen = 0;
            while ((reanLen = fileInputStream.read(buf)) != -1) {
                //读取到后,就写入到文件,通过fileOutputStream
                //即边读边写
//                fileOutputStream.write(buf);
                fileOutputStream.write(buf, 0, reanLen);//一定要使用这个方法
            }
            System.out.println("拷贝成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭输入流和输出流,释放资源
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
